﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Data;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;

namespace QuanLyKho.PhongMau
{
    public partial class Phongmau_Themsanpham : Form
    {
        public static string MaID = "0";
        public bool update = false;
        public static bool xem = false;

        public Phongmau_Themsanpham()
        {
            InitializeComponent();
            LoadData();
        }

        public void LoadData()
        {
            luNhomHang.Properties.DataSource = DataAll.SelectAll("PhongMau_NhomHang", "IdNhomHang,TenNhom", "");
            luNhomHang.Properties.Columns.Add(new LookUpColumnInfo("TenNhom"));
            luNhomHang.Properties.Columns.Add(new LookUpColumnInfo("IdNhomHang"));
            luNhomHang.Properties.DisplayMember = "TenNhom";
            luNhomHang.Properties.ValueMember = "TenNhom";
            luNhomHang.Properties.Columns["IdNhomHang"].Visible = false;
            luNhomHang.Properties.NullText = string.Empty;
            //luNhomHang.Properties.TextEditStyle = TextEditStyles.Standard;
            luNhomHang.Properties.ShowHeader = false;

            luLoaiHang.Properties.DataSource = DataAll.SelectAll("PhongMau_LoaiHang", "IDLoaiHang,TenLoaiHang", "");
            luLoaiHang.Properties.Columns.Add(new LookUpColumnInfo("TenLoaiHang"));
            luLoaiHang.Properties.Columns.Add(new LookUpColumnInfo("IDLoaiHang"));
            luLoaiHang.Properties.DisplayMember = "TenLoaiHang";
            luLoaiHang.Properties.ValueMember = "TenLoaiHang";
            luLoaiHang.Properties.Columns["IDLoaiHang"].Visible = false;
            luLoaiHang.Properties.NullText = string.Empty;
            //luLoaiHang.Properties.TextEditStyle = TextEditStyles.Standard;
            luLoaiHang.Properties.ShowHeader = false;

            luMaDangAnh.Properties.DataSource = DataAll.SelectAll("DkChung_HinhAnh", "MaAnh", " WHERE Loai = '0'");
            luMaDangAnh.Properties.Columns.Add(new LookUpColumnInfo("MaAnh"));
            //luMaDangAnh.Properties.Columns.Add(new LookUpColumnInfo("IDHinhAnh"));
            luMaDangAnh.Properties.DisplayMember = "MaAnh";
            luMaDangAnh.Properties.ValueMember = "MaAnh";
            //luMaDangAnh.Properties.Columns["MaAnh"].Visible = false;
            luMaDangAnh.Properties.NullText = string.Empty;
            luMaDangAnh.Properties.TextEditStyle = TextEditStyles.Standard;
            luMaDangAnh.Properties.ShowHeader = false;

            var data = DataAll.SelectAll("DkChung_NhanVien", "MaNhanVien,TenNhanVien", "");
            luNguoiDangKy.Properties.DataSource = data;
            luNguoiDangKy.Properties.Columns.Add(new LookUpColumnInfo("MaNhanVien"));
            luNguoiDangKy.Properties.Columns.Add(new LookUpColumnInfo("TenNhanVien"));
            luNguoiDangKy.Properties.DisplayMember = "TenNhanVien";
            luNguoiDangKy.Properties.ValueMember = "MaNhanVien";
            luNguoiDangKy.Properties.Columns["MaNhanVien"].Visible = false;
            luNguoiDangKy.Properties.NullText = string.Empty;
            luNguoiDangKy.Properties.TextEditStyle = TextEditStyles.Standard;
            //luNguoiDangKy.Properties.SearchMode = SearchMode.AutoComplete;
            luNguoiDangKy.Properties.ShowHeader = false;

            luNguoiCat.Properties.DataSource = data;
            luNguoiCat.Properties.Columns.Add(new LookUpColumnInfo("MaNhanVien"));
            luNguoiCat.Properties.Columns.Add(new LookUpColumnInfo("TenNhanVien"));
            luNguoiCat.Properties.DisplayMember = "TenNhanVien";
            luNguoiCat.Properties.ValueMember = "MaNhanVien";
            luNguoiCat.Properties.Columns["MaNhanVien"].Visible = false;
            luNguoiCat.Properties.NullText = string.Empty;
            luNguoiCat.Properties.TextEditStyle = TextEditStyles.Standard;
            //luNguoiCat.Properties.SearchMode = SearchMode.AutoComplete;
            luNguoiCat.Properties.ShowHeader = false;

            luDonVi.Properties.DataSource = DataAll.SelectAll("DkChung_DonVi", "TenDonVi", "");
            luDonVi.Properties.Columns.Add(new LookUpColumnInfo("TenDonVi"));
            luDonVi.Properties.DisplayMember = "TenDonVi";
            luDonVi.Properties.ValueMember = "TenDonVi";
            luDonVi.Properties.NullText = string.Empty;
            //luDonVi.Properties.TextEditStyle = TextEditStyles.Standard;
            luDonVi.Properties.ShowHeader = false;

            luMauSac.Properties.DataSource = DataAll.SelectAll("DkChung_MauSac", "TenMauSac", "");
            luMauSac.Properties.Columns.Add(new LookUpColumnInfo("TenMauSac"));
            luMauSac.Properties.DisplayMember = "TenMauSac";
            luMauSac.Properties.ValueMember = "TenMauSac";
            luMauSac.Properties.NullText = string.Empty;
            //luMauSac.Properties.TextEditStyle = TextEditStyles.Standard;
            luMauSac.Properties.ShowHeader = false;

            luSize.Properties.DataSource = DataAll.SelectAll("DkChung_Size", "TenSize", " WHERE Loai=N'Size bình thường'");
            luSize.Properties.Columns.Add(new LookUpColumnInfo("TenSize"));
            luSize.Properties.DisplayMember = "TenSize";
            luSize.Properties.ValueMember = "TenSize";
            luSize.Properties.NullText = string.Empty;
            //luSize.Properties.TextEditStyle = TextEditStyles.Standard;
            luSize.Properties.ShowHeader = false;

            bntLuuLai.Visible = xem;
            LoadChungTu();
            SetData();

        }

        public void SetData()
        {
            if (MaID != "0")
            {
                var data = DataAll.SelectAll("PhongMau_SanPham", "*", " WHERE IdSanPham=" + MaID);
                dtNgayThang.Value = Convert.ToDateTime(data.Rows[0]["NgayThang"]);
                txtLenhSanSuat.Text = data.Rows[0]["LenhSanXuat"].ToString();
                dtNgayLL.Value = Convert.ToDateTime(data.Rows[0]["NgayLL"]);
                luNguoiDangKy.EditValue = data.Rows[0]["NguoiDangKy"].ToString();
                luNguoiCat.EditValue = data.Rows[0]["NguoiCat"].ToString();
                //txtMaHang.Text = data.Rows[0]["MaHang"].ToString();
                luSize.EditValue = data.Rows[0]["Size"].ToString();
                txtTenHang.Text = data.Rows[0]["TenHang"].ToString();
                spLan.EditValue = data.Rows[0]["LanSanXuat"].ToString();
                txtSoLuong.Text = data.Rows[0]["SoLuong"].ToString();
                txtDonGia.Text = data.Rows[0]["DonGia"].ToString();
                luMaDangAnh.EditValue = data.Rows[0]["MaAnh"].ToString();
                luNhomHang.EditValue = data.Rows[0]["NhomHang"].ToString();
                luLoaiHang.EditValue = data.Rows[0]["LoaiHang"].ToString();
                luDonVi.EditValue = data.Rows[0]["DonVi"].ToString();
                luMauSac.EditValue = data.Rows[0]["MauSac"].ToString();
                txtKhoVai.Text = data.Rows[0]["KhoVai"].ToString();
                dtTuNgay.Value = Convert.ToDateTime(data.Rows[0]["TuNgay"]);
                dtDenNgay.Value = Convert.ToDateTime(data.Rows[0]["DenNgay"]);
                dtNgayGCNhan.Value = Convert.ToDateTime(data.Rows[0]["NgayGCNhan"]);
                txtGiacSoDo.Text = data.Rows[0]["GiacSoDo"].ToString();
                txtGhiChu.Text = data.Rows[0]["GhiChu"].ToString();
                txtSoChungTu.Text = data.Rows[0]["SoChungTu"].ToString();
                LoadImage();
            }
        }

        public void LoadChungTu()
        {
            if (MaID == "0")
            {
                txtSoChungTu.Text = "SCT" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour
                    + DateTime.Now.Minute + DateTime.Now.Second;
            }
        }

        public void UploadImage()
        {
            var openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Image file|*.jpg;*.jpeg;*.png";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                var fileInfo = new FileInfo(openFileDialog.FileName);
                if (fileInfo.Exists)
                {
                    pbAnhKho.BackgroundImage = null;
                    pbAnhKho.Image = Image.FromFile(openFileDialog.FileName);
                    /*_content = FileToByteArray(openFileDialog.FileName);
                    _fileName = fileInfo.Name;
                    _filetype = fileInfo.Extension;*/
                }
            }
        }

        private void pbAnhKho_Click(object sender, EventArgs e)
        {
            //UploadImage();
        }

        public bool CheckSP()
        {
            var datacheck = DataAll.SelectAll("PhongMau_SanPham", "MaHang", " WHERE MaHang=N'" + luMaDangAnh.EditValue + "' AND LanSanXuat=" + spLan.Text);
            if (datacheck.Rows.Count > 0)
            {
                return false;
            }
            return true;
        }

        public void ResetForm()
        {
            luMaDangAnh.EditValue = string.Empty;
            luDonVi.EditValue = string.Empty;
            luSize.EditValue = string.Empty;
            luMauSac.EditValue = string.Empty;
            luNguoiDangKy.EditValue = string.Empty;
            luNguoiCat.EditValue = string.Empty;
            luNhomHang.EditValue = string.Empty;
            luLoaiHang.EditValue = string.Empty;
            spLan.Text = "1";
            txtTenHang.Text = string.Empty;
            txtLenhSanSuat.Text = string.Empty;
            txtSoLuong.Text = string.Empty;
            txtDonGia.Text = string.Empty;
            txtKhoVai.Text = string.Empty;
            txtGiacSoDo.Text = string.Empty;
            txtGhiChu.Text = string.Empty;
            pbAnhKho.Image = null;
        }

        private void bntLuuLai_Click(object sender, EventArgs e)
        {
            if (MaID != "0")
            {
                string message = DataAll.Update("PhongMau_SanPham", " NhomHang=N'" + luNhomHang.EditValue + "', NgayThang='" + dtNgayThang.Value.ToString("MM/dd/yyyy")
                    + "', LenhSanXuat=N'" + txtLenhSanSuat.Text + "', NgayLL='" + dtNgayLL.Value.ToString("MM/dd/yyyy") + "', NguoiDangKy=N'" + luNguoiDangKy.EditValue
                    + "', NguoiCat=N'" + luNguoiCat.EditValue
                    + "', MaHang=N'" + luMaDangAnh.EditValue + "', Size=N'" + luSize.EditValue + "', TenHang=N'" + txtTenHang.Text + "', LanSanXuat=N'" + spLan.Text
                    + "', SoLuong=N'" + SplipSo(txtSoLuong.Text) + "', SLConLai=N'" + SplipSo(txtSoLuong.Text) + "', DonGia=N'" + SplipSo(txtDonGia.Text) + "', MaAnh=N'" + luMaDangAnh.EditValue
                    + "', LoaiHang='" + luLoaiHang.EditValue + "', DonVi=N'" + luDonVi.EditValue + "', MauSac='" + luMauSac.EditValue
                    + "', KhoVai=N'" + txtKhoVai.Text + "', TuNgay='" + dtTuNgay.Value.ToString("MM/dd/yyyy") + "', DenNgay='" + dtDenNgay.Value.ToString("MM/dd/yyyy")
                    + "', NgayGCNhan='" + dtNgayGCNhan.Value.ToString("MM/dd/yyyy") + "', GiacSoDo=N'" + txtGiacSoDo.Text + "', GhiChu=N'" + txtGhiChu.Text
                    + "' WHERE IdSanPham=" + MaID);
                MessageBox.Show(message.Equals("success") ? "Sửa sản phẩm thành công" : message, "Message",
                            MessageBoxButtons.OK,
                            message.Equals("success") ? MessageBoxIcon.Information : MessageBoxIcon.Error);
                Close();
            }
            else
            {
                if (CheckSP())
                {
                    string message = DataAll.InsertAll("PhongMau_SanPham", luNhomHang.EditValue + "," + dtNgayThang.Value.ToString("MM/dd/yyyy") + "," + txtLenhSanSuat.Text
                    + "," + dtNgayLL.Value.ToString("MM/dd/yyyy") + "," + luNguoiDangKy.EditValue + "," + luNguoiCat.EditValue + "," + luMaDangAnh.EditValue + "," + luSize.EditValue + "," + txtTenHang.Text
                    + "," + spLan.EditValue + "," + SplipSo(txtSoLuong.Text) + "," + SplipSo(txtSoLuong.Text) + "," + SplipSo(txtDonGia.Text) + "," + luMaDangAnh.EditValue + "," + luLoaiHang.EditValue + "," + luDonVi.EditValue
                    + "," + luMauSac.EditValue + "," + txtKhoVai.Text + "," + dtTuNgay.Value.ToString("MM/dd/yyyy") + "," + dtDenNgay.Value.ToString("MM/dd/yyyy")
                    + "," + dtNgayGCNhan.Value.ToString("MM/dd/yyyy") + "," + txtGiacSoDo.Text + "," + txtGhiChu.Text + "," + Convert.ToInt16(TrangThai.PhongMau_TaoMoi)
                    + "," + txtSoChungTu.Text + "," + DateTime.Now.ToString("MM/dd/yyyy") + "," + Main.UserID + "," + DateTime.Now.ToString("MM/dd/yyyy"));
                    if (message.Equals("success"))
                    {
                        DataAll.InsertAll("HanhTrinh", luMaDangAnh.EditValue
                                                       + "," + Convert.ToInt32(PhongBan.PhongMau)
                                                       + "," + txtSoChungTu.Text
                                                       + "," + Convert.ToInt32(TrangThai.PhongMau_TaoMoi)
                                                       + "," + luNguoiDangKy.EditValue
                                                       + "," + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff")
                                                       + "," + txtSoLuong.Text
                                                       + "," + dtTuNgay.Value.ToString("MM/dd/yyyy")
                                                       + "," + dtDenNgay.Value.ToString("MM/dd/yyyy"));
                    }
                    LoadChungTu();
                    MessageBox.Show(message.Equals("success") ? "Thêm sản phẩm thành công" : message, "Message",
                                MessageBoxButtons.OK,
                                message.Equals("success") ? MessageBoxIcon.Information : MessageBoxIcon.Error);
                    ResetForm();
                }
                else
                {
                    MessageBox.Show("Đã tồn tại mã sản phẩm và lần sản xuất", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void luMaDangAnh_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                LoadImage();
            }
        }

        private void bntThoat_Click(object sender, EventArgs e)
        {
            Close();
        }

        public void LoadImage()
        {
            var data = DataAll.SelectAll("DkChung_HinhAnh", "*", " WHERE MaAnh=N'" + luMaDangAnh.EditValue + "'");
            if (data.Rows.Count > 0)
            {
                var content = (byte[])data.Rows[0]["Anh"];
                if (content != null)
                {
                    Image newImage;
                    using (var ms = new MemoryStream(content, 0, content.Length))
                    {
                        ms.Write(content, 0, content.Length);
                        newImage = Image.FromStream(ms, true);
                    }
                    pbAnhKho.Image = newImage;
                }
                else
                {
                    pbAnhKho.Image = null;
                }
            }
            else
            {
                MessageBox.Show("Không tìm thấy mã ảnh", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public void LoaName()
        {
            try
            {
                var data = DataAll.SelectAll("NhanVien", "HoTen", " WHERE MaIDNhanVien=" + luNguoiDangKy.Text);
                if (data.Rows.Count > 0)
                {
                    luNguoiDangKy.Text = data.Rows[0][0].ToString();
                }
                else
                {
                    MessageBox.Show("Không tìm thấy nhân viên", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Không tìm thấy nhân viên", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void luMaDangAnh_EditValueChanged(object sender, EventArgs e)
        {
            var lucheck = (LookUpEdit)sender;
            if (lucheck.ItemIndex >= 0)
            {
                LoadImage();
            }
        }

        //public void CheckSo(object sender, EventArgs e)
        //{
        //    var regex = new Regex(@"^[-+]?[0-9,]*\.?[0-9,]+$");

        //    var ctrl = (Control)sender;
        //    if (regex.IsMatch(ctrl.Text) || ctrl.Text == "")
        //    {
        //    }
        //    else
        //    {
        //        MessageBox.Show(ctrl, "Bạn phải nhập kí tự số", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //        ctrl.Text = string.Empty;
        //    }
        //}

        private void luNguoiDangKy_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                LoaName();
            }
        }

        public double SplipSo(string so)
        {
            string[] temp = so.Split(',');
            string tempSo = temp.Aggregate<string, string>(null, (current, t) => current + t);
            if (string.IsNullOrEmpty(tempSo))
            {
                return 0;
            }
            return Convert.ToDouble(tempSo);
        }

        private void txtDonGia_TextChanged(object sender, EventArgs e)
        {
            try
            {
                var culture = new System.Globalization.CultureInfo("en-US");
                double valueBefore = double.Parse(txtDonGia.Text, System.Globalization.NumberStyles.AllowThousands);
                txtDonGia.Text = String.Format(culture, "{0:N0}", valueBefore);
                txtDonGia.Select(txtDonGia.Text.Length, 0);
            }
            catch (Exception)
            {

            }
            if (string.IsNullOrEmpty(txtDonGia.Text))
            {
                txtDonGia.Text = "0";
            }
        }

        private void txtSoLuong_TextChanged(object sender, EventArgs e)
        {
            try
            {
                var culture = new System.Globalization.CultureInfo("en-US");
                double valueBefore = double.Parse(txtSoLuong.Text, System.Globalization.NumberStyles.AllowThousands);
                txtSoLuong.Text = String.Format(culture, "{0:N0}", valueBefore);
                txtSoLuong.Select(txtSoLuong.Text.Length, 0);
            }
            catch (Exception)
            {

            }
            if (string.IsNullOrEmpty(txtSoLuong.Text))
            {
                txtSoLuong.Text = "0";
            }
        }
    }
}
